package personal.xjl._23java2studentdemo.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component  //告诉spring帮忙生成一个bean,Component是Controller,Service,Mapper的总称
@WebFilter("/")    //对所有的请求过滤
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径,用于判断该用户是否去登录页面
        String path = request.getRequestURI();
        if(path.contains("login")){
            filterChain.doFilter(request, response);
        }
        else if(session.getAttribute("username")!=null){
            filterChain.doFilter(request, response);
        }
        else{
            response.sendRedirect("/login");
        }


    }
}
